package com.pan.insist.util;

import lombok.extern.log4j.Log4j2;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 *     md5 加密
 * </p>
 *
 * @author kaiji
 * @since 2020/1/10 14:24
 */
@Log4j2
public class Md5Util {

    public synchronized static String getMd5(String str) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();

             //  String.getByte("utf-8")和new String(byte[],"utf-8")各是什么意思？
             //  1.返回String解码为utf-8的字节序列； 2. 使用指定字符集解码的字节数组构造一个新的String。 "iso8859-1"
            messageDigest.update(str.getBytes(StandardCharsets.ISO_8859_1));

        } catch (NoSuchAlgorithmException e) {
            log.error("md5 error: {}, {}",e.getMessage(), e);
            return null;
        }
        byte[] byteArray = messageDigest.digest();
        StringBuilder md5StrBuilder = new StringBuilder();

        for (byte b : byteArray) {
            // java代码中Integer.toHexString(b&0xff) 括号中为什么要写b&0xff? 把整数转换成16进制字符串
            if (Integer.toHexString(0xFF & b).length() == 1) {
                md5StrBuilder.append("0").append(Integer.toHexString(0xFF & b));
            } else {
                md5StrBuilder.append(Integer.toHexString(0xFF & b));
            }
        }
        return md5StrBuilder.toString();
    }
}
